﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Drawing;
using System.Net;
using System.IO;

namespace Trade.Common
{
    public class WebUtil
    {
        public static string IPAddress()
        {
            return (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null
              && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty)
              ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
              : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }

        public static Bitmap Get_img(string imgurl)
        {
            Bitmap img = null;
            HttpWebRequest req;
            HttpWebResponse res = null;
            try
            {
                System.Uri httpUrl = new System.Uri(imgurl);
                req = (HttpWebRequest)(WebRequest.Create(httpUrl));
                req.Timeout = 180000; //设置超时值10秒
                req.UserAgent = "XXXXX";
                req.Accept = "XXXXXX";
                req.Method = "GET";
                res = (HttpWebResponse)(req.GetResponse());
                img = new Bitmap(res.GetResponseStream());//获取图片流                 
                //img.Save(@"E:/" + DateTime.Now.ToFileTime().ToString() + ".png");//随机名
            }

            catch (Exception ex)
            {
                string aa = ex.Message;
            }
            finally
            {
                res.Close();
            }
            return img;
        }

        public static byte[] FileImgToBytes(string fileurl)
        {
            try
            {
                string path = System.Web.HttpContext.Current.Server.MapPath(fileurl);
                byte[] bytes = System.IO.File.ReadAllBytes(path);
                return bytes;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static byte[] UrlImgToBytes(string fileurl)
        {
            try
            {
                System.Drawing.Bitmap bm = Common.WebUtil.Get_img(fileurl);
                MemoryStream ms = new MemoryStream();
                bm.Save(ms, bm.RawFormat);
                byte[] bytes = new Byte[ms.Length];
                bytes = ms.ToArray();
                return bytes;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}
